import React, { useState } from 'react';
import { Checkbox, Row, Col, Badge, Layout, Typography } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import { 
  RightCircleOutlined, 
  RollbackOutlined,
  TrophyOutlined
} from '@ant-design/icons';
import AnimatedButton from '../components/AnimatedButton';
import AnimatedText from '../components/AnimatedText';
import LegalParticlesBackground from '../components/LegalParticlesBackground';
import LegalDecorations from '../components/LegalDecorations';
import LegalCard from '../components/LegalCard';
import AnimatedDice from '../components/AnimatedDice';

const { Content } = Layout;
const { Title, Text } = Typography;

const CaseSelect = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [selectedCases, setSelectedCases] = useState([]);
  
  // 从路由状态中获取选择的风格
  const selectedStyle = location.state?.style || {};
  
  // 案例类型选项
  const caseTypes = [
    '人格权纠纷',
    '婚姻家庭与继承纠纷',
    '物权纠纷',
    '合同与准合同纠纷',
    '侵权责任纠纷',
    '知识产权纠纷',
    '劳动争议',
    '商事纠纷'
  ];
  
  // 计算额外律迹骰数量（每多选一个案例类型获得一个律迹骰）
  const extraDice = Math.max(0, selectedCases.length - 2);
  
  const handleSelect = (checkedValues) => {
    setSelectedCases(checkedValues);
  };
  
  const handleConfirm = () => {
    if (selectedCases.length < 2) {
      alert('请至少选择两个案例类型');
      return;
    }
    
    console.log('用户选择的案例类型:', selectedCases);
    console.log('选择的风格:', selectedStyle);
    console.log('额外律迹骰数量:', extraDice);
    
    // 确保我们传递的是可序列化的数据，不包含React元素
    // 创建一个不包含任何React元素的干净对象
    const cleanStyle = selectedStyle ? {
      value: selectedStyle.value,
      label: selectedStyle.label,
      stats: selectedStyle.stats,
      description: selectedStyle.description
    } : null;
    
    // 组合游戏参数：风格 + 选择的案例类型 + 额外律迹骰
    const params = {
      style: cleanStyle,
      cases: selectedCases,
      dice: extraDice
    };
    
    console.log('传递给游戏页面的参数:', params);
    
    // 导航到游戏页面并传递参数
    navigate('/game', { state: params });
  };

  // 获取风格对应的图标
  const getStyleIcon = () => {
    switch (selectedStyle.value) {
      case 'conservative':
        return '🛡️';
      case 'balanced':
        return '⚖️';
      case 'aggressive':
        return '⚔️';
      default:
        return '📜';
    }
  };

  return (
    <Layout className="law-adventure-layout">
      {/* 粒子背景 */}
      <LegalParticlesBackground type="dustyParchment" />
      
      {/* 装饰元素 */}
      <LegalDecorations />
      
      <Content style={{ 
        padding: '40px 24px', 
        minHeight: '100vh',
        position: 'relative',
        zIndex: 1
      }}>
        <AnimatedText
          text="选择案例类型"
          type="slideDown"
          fontSize="36px"
          fontWeight="600"
          fontFamily="var(--title-font)"
          color="var(--primary-color)"
          textAlign="center"
          style={{ marginBottom: '20px' }}
        />
        
        <AnimatedText
          text="最少选择2个，最多选择8个。每多选一个类型可获得1个律迹骰"
          type="fade"
          delay={0.3}
          color="var(--secondary-color)"
          textAlign="center"
          style={{ marginBottom: '30px', display: 'block' }}
        />
        
        <div style={{ maxWidth: 800, margin: '0 auto' }}>
          {/* 显示已选择的风格 */}
          {selectedStyle && selectedStyle.value && (
            <LegalCard 
              style="parchment" 
              title={
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <span style={{ marginRight: '10px', fontSize: '24px' }}>{getStyleIcon()}</span>
                  已选择的风格
                </div>
              }
            >
              <div style={{ textAlign: 'center' }}>
                <AnimatedText
                  text={selectedStyle.label}
                  type="highlight"
                  fontWeight="bold"
                  fontSize="20px"
                  style={{ marginBottom: '10px' }}
                />
                
                <div style={{ marginTop: '10px' }}>
                  {selectedStyle.value === 'conservative' && (
                    <Text>保守型：法盾值 6，律刃值 1</Text>
                  )}
                  {selectedStyle.value === 'balanced' && (
                    <Text>均衡型：法盾值 4，律刃值 2</Text>
                  )}
                  {selectedStyle.value === 'aggressive' && (
                    <Text>激进型：法盾值 2，律刃值 3</Text>
                  )}
                </div>
              </div>
            </LegalCard>
          )}
          
          <div style={{ margin: '20px 0' }}>
            <LegalCard style="legal">
              <Checkbox.Group 
                style={{ width: '100%' }} 
                onChange={handleSelect}
                value={selectedCases}
              >
                <Row gutter={[16, 16]}>
                  {caseTypes.map((type, index) => (
                    <Col xs={24} sm={12} key={index}>
                      <Checkbox 
                        value={type}
                        className="case-checkbox"
                        style={{
                          width: '100%',
                          padding: '15px',
                          background: selectedCases.includes(type) ? 'rgba(166, 124, 0, 0.1)' : '#fff',
                          borderRadius: 4,
                          border: selectedCases.includes(type) ? '1px solid var(--secondary-color)' : '1px solid #d9d9d9',
                          fontSize: 18,
                          display: 'flex',
                          transition: 'all 0.3s',
                          boxShadow: selectedCases.includes(type) ? '0 3px 6px rgba(166, 124, 0, 0.2)' : 'none',
                          transform: selectedCases.includes(type) ? 'translateY(-2px)' : 'none'
                        }}
                      >
                        <span style={{ marginLeft: '10px' }}>{type}</span>
                      </Checkbox>
                    </Col>
                  ))}
                </Row>
              </Checkbox.Group>
            </LegalCard>
          </div>
          
          <div style={{ 
            margin: '30px 0', 
            textAlign: 'center', 
            position: 'relative'
          }}>
            <LegalCard style="scroll">
              <div style={{ 
                display: 'flex', 
                justifyContent: 'space-around',
                alignItems: 'center',
                flexWrap: 'wrap'
              }}>
                <div>
                  <AnimatedText
                    text={`已选择: ${selectedCases.length} 个案例类型`}
                    type="fade"
                    delay={0.2}
                    fontSize="18px"
                    fontWeight="bold"
                    style={{ marginBottom: '10px', display: 'block' }}
                  />
                  
                  <AnimatedText
                    text={`共获得${extraDice}个律迹骰`}
                    type="highlight"
                    delay={0.4}
                    fontSize="18px"
                    fontWeight="bold"
                    style={{ display: 'block' }}
                  />
                </div>
                
                <div style={{ position: 'relative', minWidth: '160px' }}>
                  {extraDice > 0 ? (
                    <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'center', gap: '10px' }}>
                      {[...Array(extraDice)].map((_, i) => (
                        <AnimatedDice 
                          key={i} 
                          size={60} 
                          value={0} // 统一显示问号，避免点数混淆
                          style={{ margin: '5px' }}
                        />
                      ))}
                      
                      <div style={{
                        position: 'absolute',
                        top: '-25px',
                        right: '-15px',
                        background: 'var(--adventure-color)',
                        color: 'white',
                        borderRadius: '50%',
                        width: '40px',
                        height: '40px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        fontSize: '20px',
                        boxShadow: '0 3px 6px rgba(0, 0, 0, 0.2)'
                      }}>
                        <TrophyOutlined />
                      </div>
                    </div>
                  ) : (
                    <div style={{ 
                      padding: '20px', 
                      textAlign: 'center',
                      opacity: 0.6
                    }}>
                      至少选择3个案例类型<br/>
                      获得额外律迹骰
                    </div>
                  )}
                </div>
              </div>
            </LegalCard>
          </div>
          
          <div style={{ textAlign: 'center', marginTop: '30px', display: 'flex', justifyContent: 'center', gap: '20px' }}>
            <AnimatedButton
              style="legal"
              type="primary"
              icon={<RightCircleOutlined />}
              onClick={handleConfirm}
              disabled={selectedCases.length < 2}
            >
              开始冒险
            </AnimatedButton>
            
            <AnimatedButton 
              style="scroll"
              type="default"
              icon={<RollbackOutlined />}
              onClick={() => navigate(-1)}
            >
              返回
            </AnimatedButton>
          </div>
        </div>
      </Content>
    </Layout>
  );
};

export default CaseSelect;
